package chapter06;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.atomic.AtomicMarkableReference;

@Slf4j
public class AtomicMarkableTest {
    public static void main(String[] args) throws InterruptedException {
        GarbageBag bag=new GarbageBag("装满了垃圾");
        AtomicMarkableReference<GarbageBag> ref=new AtomicMarkableReference<>(bag,true);
        log.debug("start...");
        GarbageBag prev=ref.getReference();
        log.debug(prev.toString());

        // 创建保洁员线程
        new Thread(()->{
            log.debug("保洁员开始换垃圾袋");
            bag.setDesc("空垃圾袋");
            ref.compareAndSet(bag,bag,true,false);
            log.debug(bag.toString());
        },"保洁员").start();


        Thread.sleep(1000);
        log.debug("想换一只垃圾袋");
        boolean success=ref.compareAndSet(prev,new GarbageBag("空垃圾袋"),true,false);
        log.debug("换了吗？：{}",success);
        log.debug(ref.getReference().toString());
    }
}
// 垃圾袋
class GarbageBag{

    private String desc;
    public GarbageBag(String desc){
        this.desc=desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    @Override
    public String toString() {
        return "GarbageBag{" +
                "desc='" + desc + '\'' +
                '}';
    }
}
